package com.bee.bootstrap.plugs.shiro;

import com.bee.bootstrap.plugs.redis.RedisCacheManager;
import com.bee.bootstrap.roleResource.view.UrlResourceView;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态加载URL权限过滤
 */
@Service
public class ShiroFilerChainManager {

    @Autowired
    private DefaultFilterChainManager filterChainManager;

    private Map<String, NamedFilterList> defaultFilterChains;

    @Autowired
    private RedisCacheManager redisCacheManager;

    @PostConstruct
    public void init() {
        defaultFilterChains = new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
    }

    public void initFilterChains(List<UrlResourceView> urls) {
        //1、首先删除以前老的filter chain并注册默认的
        filterChainManager.getFilterChains().clear();
        if(defaultFilterChains != null) {
            filterChainManager.getFilterChains().putAll(defaultFilterChains);
        }

        //2、循环URL Filter 注册filter chain
        urls.forEach(urlResourceView -> {
            //注册roles filters
            if (urlResourceView!=null&&!StringUtils.isEmpty(urlResourceView.getRoles())) {
                filterChainManager.addToChain(urlResourceView.getUrl(), "roles", urlResourceView.getRoles());
            }
            //注册perms filter
            if (urlResourceView!=null&&!StringUtils.isEmpty(urlResourceView.getPermissions())) {
                filterChainManager.addToChain(urlResourceView.getUrl(), "perms", urlResourceView.getPermissions());
            }
        });

    }

}
